package com.exam.kotlindemo.act

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.alex.l.utils.extens.e
import com.alex.l.utils.extens.i
import com.androidnetworking.AndroidNetworking
import com.androidnetworking.common.Priority
import com.androidnetworking.error.ANError
import com.androidnetworking.interfaces.DownloadListener
import com.exam.kotlindemo.R
import com.exam.kotlindemo.factory.ProductFactory
import com.kaopiz.kprogresshud.KProgressHUD
import java.io.File
import java.io.FileInputStream
import java.util.*


class MainActivity : AppCompatActivity() {
    private lateinit var hudProgress: KProgressHUD

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        hudProgress = KProgressHUD.create(this)
            .setStyle(KProgressHUD.Style.PIE_DETERMINATE)
            .setLabel("开始下载...")
            .setMaxProgress(100)

        downTxt()
    }

    private fun downTxt() {
        hudProgress.show()
        val url = "https://gitee.com/alexl2020/privacy-policy/raw/master/pr.properties"
        val fileName = "i.properties"
        val filePath = filesDir.absolutePath + File.separator + fileName
        AndroidNetworking.download(url, filesDir.absolutePath, fileName)
            .setTag("downloadTest")
            .setPriority(Priority.MEDIUM)
            .build()
            .setDownloadProgressListener { bytesDownloaded: Long, totalBytes: Long ->
                val progress =
                    ((bytesDownloaded as Number).toDouble() / (totalBytes as Number).toDouble() * 100).toInt()
                progress.toString().i()
                hudProgress.setProgress(progress)
            }
            .startDownload(object : DownloadListener {
                override fun onDownloadComplete() {
                    // do anything after completion
                    "Download Complete!".i()
                    hudProgress.dismiss()
                    reaf(filePath)
                }

                override fun onError(error: ANError?) {
                    // handle error
                    error.toString().e()
                    hudProgress.dismiss()
                }
            })
    }

    private fun reaf(filePath: String) {
        filePath.i()
        val file = File(filePath)
        if (file.exists()) {
            val p = Properties()
            p.load(FileInputStream(file));
            val clsName: String = p.getProperty("clsPathA")
            clsName.i()
            val product = ProductFactory().getInstance(clsName);
            product?.show()
        } else {
            "读取配置文件失败！".e()
        }

    }

}